// GenericControls.tsx
import { useEffect, useState } from 'react';
import { IconCopy, IconMinus, IconSquare, IconX } from '@tabler/icons-react'; // React 图标
import type { WebviewWindow } from '@tauri-apps/api/webviewWindow';
import styles from './GenericControls.module.css'; // 导入 CSS Modules

interface GenericControlsProps {
    appWindow: WebviewWindow;
    noSideEffect: boolean;
}

const GenericControls = ({ appWindow, noSideEffect }: GenericControlsProps) => {
    const [isMaximized, setIsMaximized] = useState(false);

    useEffect(() => {
        const closeBtn = document.getElementById('close-maximaze-wl');
        const minimizeBtn = document.getElementById('minimize-wl');
        const maximizeBtn = document.getElementById('maximaze-wl');

        const handleClose = () => appWindow.close();
        const handleMinimize = () => appWindow.minimize();
        const handleMaximize = async () => {
            if (isMaximized) {
                await appWindow.unmaximize();
                setIsMaximized(false);
            } else {
                await appWindow.maximize();
                setIsMaximized(true);
            }
        };

        // 绑定事件
        closeBtn?.addEventListener('click', handleClose);
        minimizeBtn?.addEventListener('click', handleMinimize);
        maximizeBtn?.addEventListener('click', handleMaximize);

        // 监听窗口状态
        let interval = null;
        if (!noSideEffect) {
            interval = setInterval(async () => {
                const maximized = await appWindow.isMaximized();
                setIsMaximized(maximized);
                document.body.style.borderRadius = maximized ? '0px' : '10px';
            }, 300);
        }

        // 清理函数
        return () => {
            closeBtn?.removeEventListener('click', handleClose);
            minimizeBtn?.removeEventListener('click', handleMinimize);
            maximizeBtn?.removeEventListener('click', handleMaximize);
            if (interval) clearInterval(interval);
        };
    }, [appWindow, noSideEffect, isMaximized]);

    // JSX：条件渲染图标（替代 Svelte 的 {#if}）
    return (
        <div className={styles.controls}>
            <div className={styles.minimize} id="minimize-wl">
                <IconMinus size={14} color="white" />
            </div>
            <div className={styles.maximize} id="maximaze-wl">
                {isMaximized ? (
                    <IconCopy size={14} color="white" />
                ) : (
                    <IconSquare size={12} color="white" />
                )}
            </div>
            <div className={styles.close} id="close-maximaze-wl">
                <IconX size={14} color="white" />
            </div>
        </div>
    );
};

export default GenericControls;
